﻿using System.Text;
using Microsoft.Extensions.Logging;

namespace FileCommon.Extensions;

public static class LoggerExtensions
{
    public static void LogWithLevel(this ILogger logger, LogLevel logLevel, string message, params object[] agrs)
    {
        switch (logLevel)
        {
            case LogLevel.Critical:
                logger.LogCritical(message, agrs);
                break;
            case LogLevel.Error:
                logger.LogError(message, agrs);
                break;
            case LogLevel.Warning:
                logger.LogWarning(message, agrs);
                break;
            case LogLevel.Information:
                logger.LogInformation(message, agrs);
                break;
            case LogLevel.Trace:
                logger.LogTrace(message, agrs);
                break;
            default: // LogLevel.Debug || LogLevel.None
                logger.LogDebug(message, agrs);
                break;
        }
    }

    public static void LogException(this ILogger logger, Exception ex, LogLevel? level = null)
    {
        var selectedLevel = level ?? ex.GetLogLevel();

        logger.LogWithLevel(selectedLevel, ex.Message, ex);
        LogData(logger, ex, selectedLevel);
    }
    

    private static void LogData(ILogger logger, Exception exception, LogLevel logLevel)
    {
        if (exception.Data == null || exception.Data.Count <= 0)
        {
            return;
        }

        var exceptionData = new StringBuilder();
        exceptionData.AppendLine("---------- Exception Data ----------");
        foreach (var key in exception.Data.Keys)
        {
            exceptionData.AppendLine($"{key} = {exception.Data[key]}");
        }

        logger.LogWithLevel(logLevel, exceptionData.ToString());
    }
}